package com.diyunapp.xilinapp.me;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.net.http.RequestQueue;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.selfdefine.StatusBarActivity;
import com.diyunapp.xilinapp.utils.City;
import com.diyunapp.xilinapp.utils.MyAsyncTask;
import com.diyunapp.xilinapp.utils.MyAsyncTask01;
import com.diyunapp.xilinapp.utils.MyAsyncTask02;
import com.diyunapp.xilinapp.utils.UploadUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

public class UserInfoActivity extends StatusBarActivity implements
        View.OnClickListener, UploadUtil.OnUploadProcessListener {

    @Bind(R.id.user_face)
    LinearLayout userFace;
    @Bind(R.id.user_sex)
    LinearLayout userSex;
    @Bind(R.id.real_name)
    LinearLayout realName;
    @Bind(R.id.user_email)
    LinearLayout userEmail;
    @Bind(R.id.user_phone)
    LinearLayout userPhone;
    @Bind(R.id.user_address)
    LinearLayout userAddress;

    @Bind(R.id.go_back)
    ImageView goBack;
    private String userName;
    private final static int PHOTO_WITH_CAMERA = 1;
    private final static int PHOTO_WITH_DATA = 2;

    @Bind(R.id.icons)
    ImageView icons;
    @Bind(R.id.user_sex_tv)
    TextView userSexTv;
    @Bind(R.id.real_name_tv)
    TextView realNameTv;
    @Bind(R.id.user_email_tv)
    TextView userEmailTv;
    @Bind(R.id.user_phone_tv)
    TextView userPhoneTv;
    @Bind(R.id.user_address_tv)
    TextView userAddressTv;

    private PopupWindow popupWindow;
    private PopupWindow sexPop;

    private Dialog setHeadPicture_Dialog;

    private Dialog setSex_Dialog;
    private Dialog setAddress_Dialog;
    private TextView take_photo_tv;
    private TextView select_picture_tv;
    private TextView cancel_set_tv;
    private TextView select_female_tv;
    private TextView select_serect_tv;
    private TextView select_male_tv;
    private Uri myPhotoUri;
    private String myPhotoPath;

    private static final long PICSIZELIMIT = 480000;

    //各类操作提示对话框
    private Dialog picturePrompt_Dialog;
    private TextView prompt_title_tv;
    private TextView prompt_info_tv;
    private TextView prompt_button_tv;
    private int upLoadFlag = 0;
    private AlertDialog.Builder builder = null;
    private LinearLayout login = null;
    private Dialog dialog;
    private Button button_01 = null;
    private List<City> list_city = null;
    private List<City> list_city01 = null;
    private List<City> list_city02 = null;
    private PopupMenu popupMenu = null;
    private Menu menu;;
    private int index = 0;
    private MyAsyncTask asyncTask;
    private boolean istrue = true;
    private String key;
    private  String username;
    private String member_id;
    private String realname;
    private Bitmap myNewHeadPic;
    private RequestQueue requestQueue = null;
    private int item = 1;
    private int item_01 = 1;
    private int whitch1 = 9999;
    private int whitch2 = 9999;
    private Bitmap myHeadPic_bm;
    private View headView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);
        headView = findViewById(R.id.user_set_menubar_inc);
        super.MenuWidget(headView);
        if(MainActivity.myLogin.isUpdate_head() || MainActivity.myLogin.isGet_head())
        {
            icons.setImageBitmap(MainActivity.myLogin.getTb_headPic());
        }else{
            String icons_url=MainActivity.myLogin.getHeadimge();
            Log.i("zhangxiaoxidebug", "resultinfo2=" + icons_url);
            if(icons_url!=null){
                Log.i("zhangxiaoxidebug", "resultinfo=" + icons_url);

                if(icons_url=="http://xilin.diyunkeji.com/data/upload/shop/avatar/"||icons_url.equals("http://xilin.diyunkeji.com/data/upload/shop/avatar/")){
                    icons.setImageResource(R.drawable.user_yong);
                }else if (icons_url!="http://xilin.diyunkeji.com/data/upload/shop/avatar/"){
                    GetPictureTask myPicTask = new GetPictureTask();
                    myPicTask.execute(icons_url);
                }
//            Picasso.with(this)
//                    .load(icons_url)
//                    .resize(64, 64)
//                    .centerCrop()
//                    .placeholder(R.drawable.yong)
//                    .error(R.drawable.yong)
//                    .into(icons);
 }
        }
        SharedPreferences userinfo=getSharedPreferences("user_info",MODE_PRIVATE);
         username=userinfo.getString("username","");
        member_id=userinfo.getString("member_id","");
        realname=userinfo.getString("realname","");

        realNameTv.setText(realname);
        initView();
        getInformation();
        initDiaData();

    }


    public void initView() {
        userFace.setOnClickListener(this);
        userSex.setOnClickListener(this);
        realName.setOnClickListener(this);
        goBack.setOnClickListener(this);
        //弹出的选择图片的对话框相关功能处理
        View mydefineDialogView = LayoutInflater.from(UserInfoActivity.this).inflate(R.layout.seticon_dailog, null);
        take_photo_tv = (TextView) mydefineDialogView.findViewById(R.id.take_phone_tv);
        take_photo_tv.setOnClickListener(this);
        select_picture_tv = (TextView) mydefineDialogView.findViewById(R.id.select_picture_tv);
        select_picture_tv.setOnClickListener(this);
        cancel_set_tv = (TextView) mydefineDialogView.findViewById(R.id.cancel_tv);
        cancel_set_tv.setOnClickListener(this);
        setHeadPicture_Dialog = new Dialog(UserInfoActivity.this, R.style.userinfo_dailog_style);
        setHeadPicture_Dialog.setContentView(mydefineDialogView);
        setHeadPicture_Dialog.setCanceledOnTouchOutside(false);
//各类操作提示对话框相关功能处理
        View promptView = LayoutInflater.from(UserInfoActivity.this).inflate(R.layout.dialog_prompt, null);
        prompt_title_tv = (TextView)promptView.findViewById(R.id.prompt_dialog_title);
        prompt_info_tv = (TextView)promptView.findViewById(R.id.prompt_dialog_info);
        prompt_button_tv = (TextView)promptView.findViewById(R.id.prompt_dialog_button);
        prompt_button_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(upLoadFlag == 1)
                {
                    headPicPost();
                }
                picturePrompt_Dialog.dismiss();
            }
        });
        picturePrompt_Dialog = new Dialog(UserInfoActivity.this, R.style.selfdefine_dailog_style);
        picturePrompt_Dialog.setContentView(promptView);
        picturePrompt_Dialog.setCanceledOnTouchOutside(false);
////弹出的选择性别的对话框相关功能处理
        View sexDialogView = LayoutInflater.from(UserInfoActivity.this).inflate(R.layout.setsex_dailog, null);
        select_female_tv = (TextView) sexDialogView.findViewById(R.id.select_female_tv);
        select_female_tv.setOnClickListener(this);
        select_serect_tv = (TextView) sexDialogView.findViewById(R.id.select_serect_tv);
        select_serect_tv.setOnClickListener(this);
        select_male_tv = (TextView) sexDialogView.findViewById(R.id.select_male_tv);
        select_male_tv.setOnClickListener(this);
        setSex_Dialog = new Dialog(UserInfoActivity.this, R.style.userinfo_dailog_style);
        setSex_Dialog.setContentView(sexDialogView);
        setSex_Dialog.setCanceledOnTouchOutside(false);


    }
    public void toast(String msg){
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_face:
//                popupWindow.showAsDropDown(getTopBar(), 0, (int) -ViewUtil.dip2px(this, 52));

                setHeadPicture_Dialog.show();
                break;
            case R.id.take_phone_tv:
                doTakePhoto();
                setHeadPicture_Dialog.dismiss();
                break;
            case R.id.select_picture_tv:
                pickPhoto();
                setHeadPicture_Dialog.dismiss();
                break;
            case R.id.cancel_tv:
                setHeadPicture_Dialog.dismiss();
                break;
            case R.id.prompt_dialog_button:
                picturePrompt_Dialog.dismiss();
                if(upLoadFlag == 1)
                {
                    headPicPost();
                }
                break;
            case R.id.user_sex:
//                sexPop.showAsDropDown(getTopBar(), 0, (int) -ViewUtil.dip2px(this, 52));
                setSex_Dialog.show();
                break;
            case R.id.select_serect_tv:
                upsex("保密");
                setSex_Dialog.dismiss();
                break;
            case R.id.select_male_tv:
                upsex("男");
                setSex_Dialog.dismiss();
                break;
            case R.id.select_female_tv:
                upsex("女");
                setSex_Dialog.dismiss();
                break;

            case R.id.real_name:
                Intent setInt = new Intent(this, ChangeNameActivity.class);
                startActivityForResult(setInt, 3);
                break;
            case R.id.go_back:
                finish();
                break;

        }
    }

    private void upsex(String sex) {
        userSexTv.setText(sex);
        int type = 0;
        if(sex=="保密"||sex.equals("保密")){
            type=0;
        }else if(sex=="男"||sex.equals("男")){
            type=1;
        }else if(sex=="女"||sex.equals("女")){
            type=2;
        }
        String url = ""+MainActivity.url+"act=goods&op=sex&username="+MainActivity.myLogin.getUsername()+"&sex="+type+"";
//        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=sex&username="+username+"&sex="+type+"";
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {}
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        bidFreshLv.onRefreshComplete();
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        Logger.e("=================================="+resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
//                                toast(String.valueOf(result));
                            if (result == 200) {
//                                JSONObject information = resultObject.optJSONObject("datas");
                                String date=resultObject.optString("date");
                               toast(date);
                            }else {
                                String date=resultObject.optString("date");
                                toast(date);
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();

                        }
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {

                        toast("请求失败");

                    }
                });


    }


    /**
     * 拍
     **/
    private void doTakePhoto() {
        //执行拍照前，应该先判断SD卡是否存在
        String SDState = Environment.getExternalStorageState();
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
            startActivityForResult(intent, PHOTO_WITH_CAMERA);  //用户点击了从相机获取
        } else {
            Toast.makeText(this, "没有SD卡", Toast.LENGTH_LONG).show();
        }
    }

    /***
     * 从相册中取图片
     */
    private void pickPhoto() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_PICK);
        startActivityForResult(intent, PHOTO_WITH_DATA);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        //设置头像时的返回响应
        if(requestCode == PHOTO_WITH_CAMERA || requestCode == PHOTO_WITH_DATA)
        {
            if(data == null)
            {
                prompt_title_tv.setText("提示");
                prompt_info_tv.setText("您中止了设置头像功能！");
                prompt_button_tv.setText("好的");
                picturePrompt_Dialog.show();
                return;
            }

            if (requestCode == PHOTO_WITH_DATA)
            {
                myPhotoUri = data.getData();
            }
            else if (requestCode == PHOTO_WITH_CAMERA )
            {
                myPhotoUri = data.getData();
                if(myPhotoUri == null)
                {
                    //use bundle to get data
                    Bundle bundle = data.getExtras();
                    if (bundle != null)
                    {
                        myNewHeadPic = (Bitmap) bundle.get("data"); //get bitmap
                        icons.setImageBitmap(myNewHeadPic);
                        //生成图片取个名字和路径包含类型
                        String myPhone = MainActivity.myLogin.getLoginkey();
                        if(myPhone.isEmpty())
                        {
                            myPhone = "12345678912";
                        }
                        File sd=Environment.getExternalStorageDirectory();
                        String path=sd.getPath()+"/huibao";
                        File file=new File(path);
                        if(!file.exists())
                        {
                            file.mkdir();
                        }
                        myPhotoPath = path +"/" + myPhone+"headpic.jpg";
                        saveImage(myNewHeadPic, myPhotoPath);
                        prompt_title_tv.setText("提示");
                        prompt_info_tv.setText("拍照成功，请确认上传！");
                        prompt_button_tv.setText("上传");
                        picturePrompt_Dialog.show();
                        upLoadFlag = 1;
                    }
                    else
                    {
                        prompt_title_tv.setText("提示");
                        prompt_info_tv.setText("您退出了拍照功能，或您的手机可能不支持此功能，请重试或使用相册！");
                        prompt_button_tv.setText("好的");
                        picturePrompt_Dialog.show();
                    }
                    return;
                }
            }
            String myPicpath = getPath(myPhotoUri);
            Log.i("zhangxiaoxidebug", "resultinfo=" + myPicpath);
            if((myPicpath.endsWith(".png")
                        || myPicpath.endsWith(".PNG")
                        ||myPicpath.endsWith(".JPEG")
                        ||myPicpath.endsWith(".jpeg")
                        ||myPicpath.endsWith(".jpg")
                        ||myPicpath.endsWith(".JPG") ))
                {
                    try {
                        myNewHeadPic = compScale(myPicpath);
                        icons.setImageBitmap(myNewHeadPic);
                        prompt_title_tv.setText("提示");
                        prompt_info_tv.setText("您已成功选择照片，请确认上传！");
                        prompt_button_tv.setText("上传");
                        picturePrompt_Dialog.show();
                        upLoadFlag = 1;
                    } catch (Exception e) {
                        Log.i("zhangxiaoxidebug", "resultinfo=" + e);
                        e.printStackTrace();
                    }
                }else{
                    Toast.makeText(this, "选择图片文件格式不支持，请重新选择", Toast.LENGTH_LONG).show();
                    return;
                }
        }
        if (requestCode == 3) {
            if (resultCode == 3) {
                getInformation();

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public static void saveImage(Bitmap photo, String spath)
    {
        try
        {
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(spath, false));
            photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 从图片uri中获取图片路径
     */
    public String getPath(Uri uri ) {
        if ( null == uri )
        {
            prompt_title_tv.setText("提示");
            prompt_info_tv.setText("选择的图片Uri为空，请重试或选择其他照片！");
            prompt_button_tv.setText("好的");
            picturePrompt_Dialog.show();
            return null;
        }
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
        {
            data = uri.getPath();
        }
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) )
        {
            data = uri.getPath();
        }
        else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) )
        {
            Cursor cursor = this.getContentResolver()
                    .query(uri,new String[] {MediaStore.Images.ImageColumns.DATA}, null, null, null );
            if ( null != cursor )
            {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
    public Bitmap compScale(String srcPath) throws Exception {

        int degree = getPicRotate(srcPath);
        Log.i("zhangxiaoxidebug", "resultinfo11111111="+degree);
        BitmapFactory.Options options = new  BitmapFactory.Options();
        Log.i("zhangxiaoxidebug", "resultinfo2222222222=");
        options.inJustDecodeBounds =  false;
        Log.i("zhangxiaoxidebug", "resultinfo33333333333=");
        options.inSampleSize = 4;
        Log.i("zhangxiaoxidebug", "resultinfo4444444444=");
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, options);
        Log.i("zhangxiaoxidebug", "resultinfo555555=");
        if(degree!=0)
        {
            Matrix m = new Matrix();
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            m.setRotate(degree); // 旋转angle度
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,m, true);// 从新生成图片
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        long picbytes = width*height;
        String Picname = MainActivity.myLogin.getLoginkey();
        if(Picname.isEmpty())
        {
            Picname = "12345678912";
        }
        myPhotoPath = srcPath.substring(0,srcPath.lastIndexOf("/")+1) + Picname+"headpic.jpg";
        FileOutputStream fops = new FileOutputStream(myPhotoPath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        Log.e("LogUtil", "baos当前图片压缩为：" + baos.toByteArray().length / 1024 + "kb");
        if(picbytes>PICSIZELIMIT)
        {
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
            newOpts.inJustDecodeBounds = true;
            Bitmap map = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length, newOpts);
            // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
            newOpts.inJustDecodeBounds = false;
            int w = newOpts.outWidth;
            int h = newOpts.outHeight;
            Log.e("LogUtil", "outWidth:" + w + "----------" + "outHeight:" + h);
            // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
            float ww = 1280f;// 这里设置宽度为600f
            float hh = 720f;// 这里设置高度为800f
            // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
            int be = 1;// be=1表示不缩放
            if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
                be = (int) (newOpts.outWidth / ww);
            } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
                be = (int) (newOpts.outHeight / hh);
            }
            if (be <= 0)
                be = 1;
            Log.e("LogUtil", "be:" + be);
            newOpts.inSampleSize = be;// 设置缩放比例
            map = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length, newOpts);
            ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
            map.compress(Bitmap.CompressFormat.JPEG, 100, baos1);
            Log.e("LogUtil", "baos1当前图片压缩为：" + baos1.toByteArray().length / 1024 + "kb");
            fops.write(baos1.toByteArray());
            fops.flush();
            fops.close();
            return map;
        }
        else
        {
            fops.write(baos.toByteArray());
            fops.flush();
            fops.close();
            return bitmap;
        }
    }

    /**
     * 读取图片文件旋转的角度
     * @param path 图片绝对路径
     * @return 图片旋转的角度
     */
    public static int getPicRotate(String path) {
        int degree  = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return degree;
    }

    private void headPicPost()
    {
//        toast("11");
        String uploadURL = ""+MainActivity.url+"act=goods&op=change_head";
        UploadUtil uploadUtil = UploadUtil.getInstance();
        uploadUtil.setOnUploadProcessListener(this); //设置监听器监听上传状态
        Map<String, String> params = new HashMap<String, String>();
        params.put("member_id", MainActivity.myLogin.getMemberid());
        params.put("uploadedfile", "12345678912headpic.jpg");

        uploadUtil.uploadFile(myPhotoPath,uploadURL,params);
    }

    public void getInformation() {
//        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=people_info&username="+username+"";
        String url = ""+MainActivity.url+"act=goods&op=people_info&username="+ MainActivity.myLogin.getUsername()+"";

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(100000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        bidFreshLv.onRefreshComplete();
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        Logger.e("=================================="+resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
                            if (result == 200) {
                                JSONObject resultObject1 = resultObject.optJSONObject("date");
//                                for (int i = 0; i < listArray.length(); i++) {
//                                    JSONObject recordObject = listArray.optJSONObject(listArray);
                                    int member_sex=resultObject1.optInt("member_sex");
                                    String member_truename=resultObject1.optString("member_truename");
                                    String member_email=resultObject1.optString("member_email");
                                    String member_mobile=resultObject1.optString("member_mobile");

                                    String member_areainfo=resultObject1.optString("member_areainfo");
                                if(member_sex==0){
                                    userSexTv.setText("保密");
                                }else if(member_sex==1){
                                    userSexTv.setText("男");
                                }else if (member_sex==2){
                                    userSexTv.setText("女");
                                }
                                if(member_truename=="null"){
                                    realNameTv.setText("未设置");
                                }else{
                                    realNameTv.setText(member_truename);
                                }
                                    userEmailTv.setText(member_email);
                                if(member_mobile=="null"){
                                    userPhoneTv.setText("未绑定");
                                }else{
                                    userPhoneTv.setText(member_mobile);
                                }
                                if(member_areainfo=="null"){
                                    userAddressTv.setText("未设置");
                                }else{
                                    userAddressTv.setText(member_areainfo);
                                }
                            } else {
                                toast("当前暂无数据");
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
                        toast("请求失败");
                    }
                });
    }
    private void initDiaData() {
        userAddressTv.setOnClickListener(onButtonClick);
        list_city = new ArrayList<City>();
        list_city01 = new ArrayList<City>();
        list_city02 = new ArrayList<City>();
//        requestQueue = Volley.newRequestQueue(getApplicationContext());
        asyncTask = new MyAsyncTask(list_city);

        MyAsyncTask02 asyncTask02 = new MyAsyncTask02(list_city02);


        asyncTask
                .execute(""+MainActivity.url+"act=goods&op=people_city");
    }
    private View.OnClickListener onButtonClick = new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            // TODO Auto-generated method stub

            login = (LinearLayout) View.inflate(UserInfoActivity.this,
                    R.layout.alertdialog, null);
            button_01 = (Button) login.findViewById(R.id.button1);


            for (int i = 0; i < 3; i++) {
                if (i == 0) {
                    ((RelativeLayout) (login.getChildAt(2)))
                            .setOnClickListener(onButtonClick1);
                } else {
                    ((RelativeLayout) (login.getChildAt(2 * i+2)))
                            .setOnClickListener(onButtonClick1);
                }
            }


            builder = new AlertDialog.Builder(UserInfoActivity.this);
            builder.setOnKeyListener(new DialogInterface.OnKeyListener() {

                @Override
                public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
                    // TODO Auto-generated method stub
                    whitch1=9999;
                    whitch2=9999;
                    return false;
                }
            });
            builder.setCancelable(false);
            builder.setCancelable(true).setView(login);

//            builder.setTitle(
//                    "                地区选择")
//                    .setCancelable(true).setView(login);
//            View mTitleView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.alera, null);
//            builder.setCustomTitle(mTitleView);
            builder.create();
            dialog = builder.show();
        }
    };
    private View.OnClickListener onButtonClick1 = new View.OnClickListener() {

        public String index_01 = null;

        @Override
        public void onClick(View arg0) {

            // TODO Auto-generated method stub
            final int index = login.indexOfChild(arg0) / 2-1;
            // initOnClickListener(index);
            final TextView textview1 = (TextView) login
                    .findViewById(R.id.textView_shenfen);
            final TextView textview2 = (TextView) login
                    .findViewById(R.id.textView_scity);
            final TextView textview3 = (TextView) login
                    .findViewById(R.id.textView_quyu);
            final TextView textview4 = (TextView) login
                    .findViewById(R.id.textView_shenfen1);
            final TextView textview5 = (TextView) login
                    .findViewById(R.id.textView_scity1);
            final TextView textview6 = (TextView) login
                    .findViewById(R.id.textView_quyu1);
            final Button button_01 = (Button) login.findViewById(R.id.button1);
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    UserInfoActivity.this);
               int index_0;
            // 指定下拉列表的显示数据
              builder.setCancelable(true);
               if (index == 0) {
                String[] str = new String[list_city.size()];
                String[] cities = { "广州", "上海", "北京", "香港", "澳门" };
                for (int i = 0; i < list_city.size(); i++) {

                    str[i] = list_city.get(i).getArea_name().toString();
                }
                // 设置一个下拉的列表选择项
                builder.setItems(str, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (index == 0) {
                            textview1.setText(list_city.get(which)
                                    .getArea_name().toString());
                            textview4.setText(list_city.get(which).getArea_id().toString());
                            index_01 = list_city.get(which).getArea_id();
                            MyAsyncTask01 asyncTask01 = new MyAsyncTask01(list_city01);
                            asyncTask01
                                    .execute(""+MainActivity.url+"act=goods&op=city&area_id="
                                            +list_city.get(which).getArea_id());
                            whitch1 = which;
                            list_city01.clear();
                        }
                    }
                });
//                item = 0;
//                item_01 = 1;
                builder.show();
            }else if (index == 1) {
                if (whitch1 != 9999) {
                    String[] str = new String[list_city01.size()];

                    for (int i = 0; i < list_city01.size(); i++) {

                        str[i] = list_city01.get(i).getArea_name().toString();

                    }
                    // 设置一个下拉的列表选择项
                    builder.setItems(str, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            textview2.setText(list_city01.get(which)
                                    .getArea_name().toString());
                            textview5.setText(list_city01.get(which).getArea_id().toString());
                            index_01 = list_city01.get(which).getArea_id();
                            String ci= textview4.getText().toString().trim();
//                                toast(ci);
                            int ci1= Integer.parseInt(ci);
                            if(ci1==32||ci1==34||ci1==33) {
                                toast("无下属区域");
                                whitch2 = 9999;

                            }else {
                                MyAsyncTask02 asyncTask02 = new MyAsyncTask02(
                                        list_city02);
                                asyncTask02
                                        .execute("" + MainActivity.url + "act=goods&op=city&area_id="
                                                + list_city01.get(which)
                                                .getArea_id());
                                list_city02.clear();
                                whitch2 = which;
                            }
                        }
                    });
//                    item = 1;
//                    item_01 = 0;
                    builder.show();
                }
                else {
                    Toast.makeText(getApplicationContext(), "请选择省份",
                            Toast.LENGTH_SHORT).show();
                }
            } else if (index == 2) {
                if (whitch2 != 9999) {
                    String[] str = new String[list_city02.size()];

                    for (int i = 0; i < list_city02.size(); i++) {

                        str[i] = list_city02.get(i).getArea_name().toString();
//                        item = 1;
                    }

                    // 设置一个下拉的列表选择项
                    builder.setItems(str, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            textview3.setText(list_city02.get(which)
                                    .getArea_name().toString());
                            textview6.setText(list_city02.get(which).getArea_id().toString());
//                            list_city02.clear();
//                            item = 0;
                        }
                    });
                    builder.show();
                } else {
                    Toast.makeText(getApplicationContext(), "请选择城市",
                            Toast.LENGTH_SHORT).show();
                }
            }
            button_01.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String tx1=null;
                    if(textview1.getText().toString()=="请选择"||textview1.getText().toString().equals("请选择")){
                        tx1="";
                    }else{
                        tx1=textview1.getText().toString();
                    }
                    String tx2=null;
                    if(textview2.getText().toString()=="请选择"||textview2.getText().toString().equals("请选择")){
                        tx2="";
                    }else{
                        tx2=textview2.getText().toString();
                    }
                    String tx3=null;
                    if(textview3.getText().toString()=="请选择"||textview3.getText().toString().equals("请选择")){
                        tx3="";
                    }else{
                        tx3=textview3.getText().toString();
                    }
                    String area=tx1+""+tx2+""+tx3;                    userAddressTv.setText(area);
//                    address_id.setText(textview4.getText().toString());
//                    address_id1.setText(textview5.getText().toString());
//                    address_id2.setText(textview6.getText().toString());
                    sureAddress(area);
                    item = 1;
                    item_01 = 1;
                    dialog.dismiss();

//                        list_city.get(i).getArea_id();
                }
            });
        }

    };

    private void sureAddress(String area) {
        String url = ""+MainActivity.url+"act=goods&op=qdcity&member_id="+MainActivity.myLogin.getMemberid()+"&area_info="+area+"";
//        String url = "http://www.xilingou.com/mobile/index.php?act=member_address&op=address_del&key="+key+"&address_id="+id+"";
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {}
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        bidFreshLv.onRefreshComplete();
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        Logger.e("=================================="+resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
//                                toast(String.valueOf(result));
                            if (result == 200) {

                                String date=resultObject.optString("date");
//                                if (state.equals("1")){
                                    toast(date);
//                                }else{
//
//                                    toast(error);
//                                }
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();

                        }
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {

                        toast("请求失败");

                    }
                });
    }

    public String index_01;

    @Override
    public void onUploadDone(int responseCode, String message) {
// TODO Auto-generated method stub
        Message myMes = Message.obtain();
        myMes.arg1 = responseCode;
        myMes.obj = message;
        myPicupHandle.sendMessage(myMes);
    }

    @Override
    public void onUploadProcess(int uploadSize) {
        // TODO Auto-generated method stub
        Message myMes = Message.obtain();
        myMes.arg1 = 10;
        myMes.arg2 = uploadSize;
        myPicupHandle.sendMessage(myMes);
    }
    private Handler myPicupHandle = new Handler(){

        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case UploadUtil.UPLOAD_SUCCESS_CODE:
                    MainActivity.myLogin.setTb_headPic(myNewHeadPic);
                    MainActivity.myLogin.setUpdate_head(true);
                    setResult(1);
                    prompt_title_tv.setText("提示");
                    prompt_info_tv.setText("头像修改成功！");
                    prompt_button_tv.setText("好的");
                    prompt_button_tv.setClickable(true);
                    picturePrompt_Dialog.show();
                    upLoadFlag = 2;
                    break;
                case UploadUtil.UPLOAD_SERVER_ERROR_CODE:
                    prompt_title_tv.setText("提示");
                    String error = msg.obj.toString();
                    prompt_info_tv.setText(error);
                    prompt_button_tv.setText("好的");
                    prompt_button_tv.setClickable(true);
                    picturePrompt_Dialog.dismiss();
                    upLoadFlag = 2;
                    break;
                case 10:
                    MainActivity.myLogin.setTb_headPic(myNewHeadPic);
                    MainActivity.myLogin.setUpdate_head(true);
                    prompt_title_tv.setText("上传进度");
                    prompt_info_tv.setText("已上传"+msg.arg2+"k");
                    prompt_button_tv.setText("请稍后···");
//                    prompt_button_tv.setClickable(false);
                    picturePrompt_Dialog.show();
                    break;
                default:
                    break;
            }
        };
    };
    @Override
    public void initUpload(int fileSize) {

    }
    private class GetPictureTask extends AsyncTask<String, String, Integer> {
        @Override
        protected Integer doInBackground(String... params) {
            String pictureUrl = params[0];
            URL imgUrl = null;
            try {
                imgUrl = new URL(pictureUrl);
                HttpURLConnection conn = (HttpURLConnection)imgUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                InputStream is = conn.getInputStream();
                myHeadPic_bm = BitmapFactory.decodeStream(is);
                is.close();
                return 1;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return 10;
            }catch(IOException e){
                e.printStackTrace();
                return 11;
            }
        }
        @Override
        protected void onPostExecute(Integer result) {
            switch (result) {
                case 1:
                    icons.setImageBitmap(myHeadPic_bm);
                    break;
                case 10:
                    break;
                case 11:
                    break;
                default:
                    break;
            }
            super.onPostExecute(result);
        }
    }

}
